<?php

namespace Modules\Category\Http\Controllers;

use Illuminate\Support\Facades\Log; // 引入 Log 类
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Category\Models\Category;
use Illuminate\Validation\Rule;
use Modules\Category\Helpers\helpers2;
use Modules\Category\Helpers\helpers;
class MenuController extends Controller
{
    //菜单列表
    public function index(Request $request)
    {
        $tree = cache_menu_all();
        cache()->forget('menu_tree_all_menu'); // 清除正确的缓存键
        return cat_success($tree);
    }
    //菜单详情
    public function show(Request $request, $id)
    {
        $tree = Category::find($id);
        if (!$tree) return cat_error('分类不存在');
        cache()->forget('menu_tree_menu'); // 清除正确的缓存键
        return cat_success($tree);
    }
     public function store(Request $request) {
        // 验证
        $input=$this->checkInput($request);
        if(!is_array($input)) return $input;
        $pid=$input['pid'];
        $level=$input['level'];
        // 插入数据
        $category = Category::create([
            'name'   => $request->name,
            'pid'    => $pid,
            'level'  => $level,
            'group'  => $input['group'],
            'status' => $request->input('status', 1),
        ]);
        clear_cache_category();
        return cat_success($category, '创建成功', 201);
    }
    public function checkInput(Request $request){
            $request->validate(
                ['name'=>'required|max:16|unique:categories,name'],
                ['name.required'=>'分类名称不能为空','name.unique'=>'分类名称已存在']
            );
            $group = $request->input('group', 'menu');
            $pid   = $request->input('pid', 0);
            $level = $pid ? (Category::find($pid)?->level + 1 ?? null) : 1;
            if ($pid && !$level) return cat_error('父级分类不存在');
            if ($level > 3) return cat_error('分类层级不能超过3级');
            return ['pid'=>$pid,'level'=>$level,'group'=>$group];
    }
}

